package com.kd.juhaowan.ui.fragment;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.CommonApi;
import com.kd.juhaowan.http.api.ReciveDjqApi;
import com.kd.juhaowan.http.api.ReciveGiftApi;
import com.kd.juhaowan.http.model.FuliResult;
import com.kd.juhaowan.http.model.GiftModel;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.http.model.HttpListData;
import com.kd.juhaowan.http.model.ShequModel;
import com.kd.juhaowan.ui.DocumentActivity;
import com.kd.juhaowan.ui.GameDetailActivity;
import com.kd.juhaowan.ui.GameDetailActivity2;
import com.kd.juhaowan.ui.MainActivity;
import com.kd.juhaowan.ui.MoreDjqActivity;
import com.kd.juhaowan.ui.MoreGiftActivity;
import com.kd.juhaowan.ui.adapter.BaseRecyclerViewAdapter;
import com.kd.juhaowan.ui.adapter.BaseViewHolder;
import com.kd.juhaowan.ui.dialog.ConfirmDialog;
import com.kd.juhaowan.ui.holder.Fuli648ViewHolder;
import com.kd.juhaowan.ui.holder.FuliDjqViewHolder;
import com.kd.juhaowan.ui.holder.FuliShequViewHolder;
import com.kd.juhaowan.ui.listener.OnItemDianzanListener;
import com.kd.juhaowan.utils.DeviceUtil;
import com.kd.juhaowan.utils.LogUtil;
import com.kd.juhaowan.view.FulliScollTextView;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class FuliFragment extends BaseFragment implements OnItemDianzanListener {


    @BindView(R.id.fragment_home_scrollTextView)
    FulliScollTextView mScrollTextView;

    @BindView(R.id.fuli_648list)
    RecyclerView m648ListView;
    @BindView(R.id.fuli_djqlist)
    RecyclerView mDjqListView;
    @BindView(R.id.fuli_shequlist)
    RecyclerView mShequListView;
    private FuliResult headModel;
    private BaseRecyclerViewAdapter<Fuli648ViewHolder, GiftModel> m648Adapter;
    private BaseRecyclerViewAdapter<FuliDjqViewHolder, GiftModel> mDjqAdapter;
    private BaseRecyclerViewAdapter<FuliShequViewHolder, ShequModel> msheqAdapter;

    @Override
    protected void onButterKnifeCreateViewAfter() {
        super.onButterKnifeCreateViewAfter();
        setAdapter();
//        initData();
    }
//    private boolean isFirst = true;
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtil.debugLog(((getActivity()!=null)?((MainActivity)getActivity()).getCurrentItem():false)+"Fuli onHiddenChanged"+isVisibleToUser);
        if(isVisibleToUser&&getActivity()!=null&&((MainActivity)getActivity()).getCurrentItem()==2){

            initData();
        }
    }

    @Override
    protected void reInitDate() {
        initData();
    }

    private void initData(){
        EasyHttp.post(this).api(new CommonApi("api/welfare/index")).request(new HttpCallbackProxy<HttpData<FuliResult>>(this){
            @Override
            public void onHttpSuccess(HttpData<FuliResult> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                headModel = result.getData();
                m648Adapter.resetAdapterData(headModel.getGiftpack());
                mDjqAdapter.resetAdapterData(headModel.getVoucher());
                mScrollTextView.setData(headModel.getClaim_record());
//                        LogUtil.debugLog(result.getData().getAccess_token());
//                        Toast.makeText(AccountLoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
//                bannerModels = result.getData();

//                onRefresh(getSmartRefreshLayout());
            }
        });
        EasyHttp.post(this).api(new CommonApi("api/welfare/CommunityActivities")).request(new HttpCallbackProxy<HttpListData<ShequModel>>(this){
            @Override
            public void onHttpSuccess(HttpListData<ShequModel> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                msheqAdapter.resetAdapterData(result.getData().getList());
//                        LogUtil.debugLog(result.getData().getAccess_token());
//                        Toast.makeText(AccountLoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
//                bannerModels = result.getData();

//                onRefresh(getSmartRefreshLayout());
            }
        });
    }



    private void setAdapter(){
        m648Adapter = new BaseRecyclerViewAdapter<Fuli648ViewHolder, GiftModel>() {
            @NonNull
            @Override
            public Fuli648ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View view = inflater.inflate(R.layout.item_fuli_648, null, false);
                Fuli648ViewHolder holder = new Fuli648ViewHolder(view);
                holder.setOnItemClickListener(getOnItemClickListener());
                return holder;
            }

            @Override
            public void onBindViewHolder(@NonNull Fuli648ViewHolder holder, int position) {
                holder.setDate(getItem(position));
            }
        };

        m648Adapter.setOnItemClickListener(this);
        m648Adapter.resetAdapterData(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);

        m648ListView.setLayoutManager(layoutManager);
        m648ListView.setAdapter(m648Adapter);


        mDjqAdapter = new BaseRecyclerViewAdapter<FuliDjqViewHolder, GiftModel>() {
            @NonNull
            @Override
            public FuliDjqViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View view = inflater.inflate(R.layout.item_fuli_djq, null, false);
                FuliDjqViewHolder holder = new FuliDjqViewHolder(view);
                holder.setOnItemClickListener(getOnItemClickListener());
                return holder;
            }

            @Override
            public void onBindViewHolder(@NonNull FuliDjqViewHolder holder, int position) {
                holder.setDate(getItem(position));
            }
        };
        mDjqAdapter.setOnItemClickListener(this);
        mDjqAdapter.resetAdapterData(null);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        layoutManager2.setOrientation(RecyclerView.VERTICAL);

        mDjqListView.setLayoutManager(layoutManager2);
        mDjqListView.setAdapter(mDjqAdapter);
//        mDjqListView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                return motionEvent.getAction()==MotionEvent.ACTION_MOVE;
//            }
//        });

        msheqAdapter = new BaseRecyclerViewAdapter<FuliShequViewHolder, ShequModel>() {
            @NonNull
            @Override
            public FuliShequViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View view = inflater.inflate(R.layout.item_fuli_shequ, null, false);
                FuliShequViewHolder holder = new FuliShequViewHolder(view);
                holder.setOnItemClickListener(getOnItemClickListener());
                return holder;
            }

            @Override
            public void onBindViewHolder(@NonNull FuliShequViewHolder holder, int position) {
                holder.setDate(getItem(position));
            }
        };

        msheqAdapter.setOnItemClickListener(this);
        msheqAdapter.resetAdapterData(null);
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(getContext());
        layoutManager3.setOrientation(RecyclerView.VERTICAL);

        mShequListView.setLayoutManager(layoutManager3);
        mShequListView.setAdapter(msheqAdapter);
    }


    @OnClick(R.id.fuli_648list_more)
    public void onMoregiftClick(){
        startActivity(new Intent(getContext(), MoreGiftActivity.class));
    }
    @OnClick(R.id.fuli_djq_more)
    public void onMoreDjqClick(){
        startActivity(new Intent(getContext(), MoreDjqActivity.class));
    }


    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.fragment_fuli;
    }

    @Override
    public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int position) {
        if(viewHolder instanceof FuliShequViewHolder){

            Intent intent= new Intent(getContext(), DocumentActivity.class);
            intent.putExtra("shequ_id",msheqAdapter.getItem(position).getId());
            startActivity(intent);
        }

    }




    private ConfirmDialog dialog = null;
    @Override
    public void onItemDianzanClick(BaseViewHolder viewHolder, int position) {
        if(viewHolder instanceof Fuli648ViewHolder){
            GiftModel model = m648Adapter.getItem(position);
            EasyHttp.post(this).api(new ReciveGiftApi(model.getId(),model.getGame_id(), DeviceUtil.isInstallApp(getContext(),model.getGame_package_name())?1:2)).request(new HttpCallbackProxy<HttpData<GiftModel>>(this){
                @Override
                public void onHttpSuccess(HttpData<GiftModel> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    model.setIs_receive(1);
//                    model.setCode(result.getData().getCode());
                    m648Adapter.notifyItemChanged(position,model);
                    startDownload(model);

                    ConfirmDialog.Builder builder = new ConfirmDialog.Builder(getContext());
                    builder.setMessage(result.getMessage());
                    builder.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            gotGameInfo(model);
                            dialog.dismiss();
                        }
                    });
                    dialog = builder.create();
                    dialog.show();

                }
            });
        }else if(viewHolder instanceof FuliDjqViewHolder){
            GiftModel model = mDjqAdapter.getItem(position);
            EasyHttp.post(this).api(new ReciveDjqApi(model.getId(), DeviceUtil.isInstallApp(getContext(),model.getGame_package_name())?1:2)).request(new HttpCallbackProxy<HttpData<GiftModel>>(this){
                @Override
                public void onHttpSuccess(HttpData<GiftModel> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    model.setIs_receive(1);
//                    model.setCode(result.getMessage());
                    mDjqAdapter.notifyItemChanged(position,model);
                    startDownload(model);
                    ConfirmDialog.Builder builder = new ConfirmDialog.Builder(getContext());
                    builder.setMessage(result.getMessage());
                    builder.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            gotGameInfo(model);
                            dialog.dismiss();
                        }
                    });
                    dialog = builder.create();
                    dialog.show();
                }
            });
        }
    }

    public void gotGameInfo(GiftModel model){
        if(DeviceUtil.isInstallApp(getContext(),model.getGame_package_name())){
            final Intent intent = getContext().getPackageManager().getLaunchIntentForPackage(model.getGame_package_name());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            startActivity(intent);
        }else{
            Intent intent= new Intent(getActivity(), GameDetailActivity.class);
            intent.putExtra("id",model.getGame_id());
            intent.putExtra("startdownload",true);
            startActivity(intent);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(loadingid!=0){
            FileDownloader.getImpl().pause(loadingid);
        }
    }

    private int loadingid=0;

    private void startDownload(GiftModel model){
        StringBuilder builder = new StringBuilder(model.getGame_package_name().trim());
//        builder.append(gameid);
        builder.append(".apk");
        File file = new File(getContext().getExternalCacheDir(), builder.toString());
//        mSinglePath = FileDownloadUtils.getDefaultSaveRootPath()+
////                File.separator+"feifei_save"+
//                File.separator+model.getGame_package_name().trim()+".apk";;
        String mSinglePath = file.getAbsolutePath();
        BaseDownloadTask singleTask = FileDownloader.getImpl().create(model.getGame_urlfile())
//                .setPath(mSinglePath,false)
                .setPath(mSinglePath,false)
                .setCallbackProgressTimes(1000)
                .setMinIntervalUpdateSpeed(1000);
        loadingid = singleTask.start();

    }
}
